import sys
from  PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class TableDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.initUi()
    def initUi(self):
        self.setWindowTitle("QtableWidget案例")
        self.resize(400,300)
        conLayout=QHBoxLayout()
        self.tablewidget=QTableWidget()
        self.tablewidget.setRowCount(4)
        self.tablewidget.setColumnCount(3)
        conLayout.addWidget(self.tablewidget)
        self.tablewidget.setHorizontalHeaderLabels(['姓名','性别','年纪',"图片"])
        self.tablewidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        newItem=QTableWidgetItem("张三")
        self.tablewidget.setItem(0,0,newItem)
        newItem = QTableWidgetItem("男")
        self.tablewidget.setItem(0, 1, newItem)
        newItem = QTableWidgetItem("20")
        self.tablewidget.setItem(0, 2, newItem)

        newItem = QTableWidgetItem("李四")
        self.tablewidget.setItem(1, 0, newItem)
        newItem = QTableWidgetItem("女")
        self.tablewidget.setItem(1, 1, newItem)
        newItem = QTableWidgetItem("21")
        self.tablewidget.setItem(1, 2, newItem)
        self.tablewidget.setContextMenuPolicy(Qt.CustomContextMenu)#允许右键菜单
        self.tablewidget.customContextMenuRequested.connect(self.getMenu)


        self.setLayout(conLayout)

    def getMenu(self,pos):
        row_num=-1
        for i in self.tablewidget.selectionModel().selection().indexes():
            row_num=i.row()
        if row_num<2:
            menu=QMenu()
            item1=menu.addAction("选项1")
            item2 = menu.addAction("选项2")
            item3 = menu.addAction("选项3")
            action=menu.exec_(self.tablewidget.mapToGlobal(pos))
            if action==item1:
                print("选了1文字内容是:",self.tablewidget.item(row_num,0).text(),self.tablewidget.item(row_num,1).text(),self.tablewidget.item(row_num,2).text())
            elif action==item2:
                print("选了2文字内容是:", self.tablewidget.item(row_num, 0).text(), self.tablewidget.item(row_num, 1).text(),
                      self.tablewidget.item(row_num, 2).text())
            elif action==item3:
                print("选了3文字内容是:", self.tablewidget.item(row_num, 0).text(), self.tablewidget.item(row_num, 1).text(),
                      self.tablewidget.item(row_num, 2).text())
            else:
                return

if __name__ == '__main__':
    app=QApplication(sys.argv)
    table=TableDemo()
    table.show()
    sys.exit(app.exec_())